package com.sfh.story;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.sfh.story.entrty.Story;

import android.os.Handler;
import android.os.Message;

public class LoadHtml
{
	public interface IStoryList
	{
		public void load(List<Story> mList);
	}

	private List<Story> mList = new ArrayList<Story>();
	private IStoryList mICallBack = null;

	private Handler mHandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			if (mICallBack != null)
			{
				mICallBack.load(mList);
			}
			super.handleMessage(msg);
		}

	};

	public void start(final String url, IStoryList callBack)
	{
		this.mICallBack = callBack;
		new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				parseHtml(url);
			}
		}).start();
	}

	private void parseHtml(String url)
	{
		try
		{
			URL mUrl = new URL(url);
			Document mDocument = Jsoup.parse(mUrl, 50000);
			Elements mElements = mDocument.select("a[href]");

			for (Element element : mElements)
			{
				String text = element.text();
				String target = element.attr("target");
				String mClass = element.attr("class");
		
				
				if ("_blank".equals(target) && "liebiao".equals(mClass))
				{
					String herf = element.attr("href");
					System.out.println("herf = "+herf);
					Story mStory = new Story();
					mStory.name = text;
					mStory.address = herf;
					mList.add(mStory);
				}
			}
			
			

			mHandler.sendEmptyMessage(0);

		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}
}
